<template>
  <div class="ReaderAvailableBooks">
    <h2>可借阅图书</h2>
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="图书名称">
        <el-input v-model="searchForm.bookname" placeholder="请输入图书名称"></el-input>
      </el-form-item>
      <el-form-item label="作者">
        <el-input v-model="searchForm.bookauthor" placeholder="请输入作者"></el-input>
      </el-form-item>
      <el-form-item label="图书类别">
        <el-select v-model="searchForm.booktypeid" placeholder="请选择类别" clearable>
          <el-option
              v-for="type in bookTypes"
              :key="type.booktypeid"
              :label="type.booktypename"
              :value="type.booktypeid">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchBooks">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="availableBooks" style="width: 100%" v-loading="loading">
      <el-table-column label="图片" width="120px">
        <template slot-scope="scope">
          <img :src="baseurl+'/'+scope.row.bookimg" alt="图书封面" style="width: 80px; height: auto; display: block; margin: 0 auto; object-fit: contain;">
        </template>
      </el-table-column>

      <el-table-column prop="bookname" label="图书名称"></el-table-column>
      <el-table-column prop="bookauthor" label="作者"></el-table-column>
      <el-table-column prop="bookprice" label="价格"></el-table-column>
      <el-table-column prop="booktypename" label="类别"></el-table-column>
      <el-table-column label="状态" width="100px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isborrowed === 0 ? 'success' : 'info'">
            {{ scope.row.isborrowed === 0 ? '可借阅' : '已借出' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="primary"
              @click="handleBorrow(scope.row)"
              :disabled="scope.row.isborrowed === 1"
          >
            {{ scope.row.isborrowed === 0 ? '借阅' : '已借出' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total"
        background
        style="margin-top: 20px; text-align: right;"
    ></el-pagination>
  </div>
</template>

<script>
import { getbookinfopage, borrowBook } from '@/api/api'; // 现在 getBookList 将匹配 api.js 中的函数名
import { getbookType } from '@/api/api';

export default {
  name: 'ReaderAvailableBooks',
  data() {
    return {
      availableBooks: [],
      loading: false,
      currentPage: 1,
      pageSize: 5,
      total: 0,
      searchForm: {
        bookname: '',
        bookauthor: '',
        booktypeid: null,
        isborrowed: 0 // 只查询未借出的图书 (可根据需求调整，如果需要显示所有状态)
      },
      bookTypes: [],
      baseurl:process.env.VUE_APP_BASE_API,
    };
  },
  created() {
    this.fetchBookTypes();
    this.fetchAvailableBooks();
  },
  methods: {
    fetchBookTypes() {
      getbookType().then(res => {
        if (res.code === 200 && res.data && res.data.children) {
          this.bookTypes = res.data.children;
        } else {
          this.$message.error(res.msg || '获取图书类别失败');
        }
      }).catch(error => {
        console.error("获取图书类别失败:", error);
        this.$message.error('获取图书类别异常');
      });
    },
    fetchAvailableBooks() {
      this.loading = true;
      const queryParams = { ...this.searchForm };
      // 如果你想在列表中看到所有图书（包括已借出），而不仅仅是可借阅的，
      // 那么在这里删除 isborrowed 属性，让后端返回所有图书。
      // delete queryParams.isborrowed; // 根据后端接口实际行为决定是否删除

      getbookinfopage(queryParams, this.currentPage) // 这里调用的是 getBookList
          .then(res => {
            if (res.code === 200) {
              this.availableBooks = res.data.list;
              this.total = res.data.total;
            } else {
              this.$message.error(res.msg || '获取可借阅图书失败');
            }
          })
          .catch(error => {
            console.error("获取可借阅图书请求失败:", error);
            this.$message.error('获取可借阅图书异常，请稍后再试');
          })
          .finally(() => {
            this.loading = false;
          });
    },
    handleBorrow(row) { // 传入的是整个 row 对象
      const username = localStorage.getItem('username'); // 确保从 localStorage 获取到 username
      console.log("--- 借阅前检查 ---");
      console.log("从 localStorage 获取的 username:", username, typeof username);
      console.log("即将传递的 bookid:", row.bookid); // 修正：从 row.bookid 获取

      if (!username) {
        this.$message.error("未获取到用户信息，请重新登录！");
        // 可以考虑跳转到登录页：this.$router.push('/login');
        return;
      }

      // 再次确认借阅操作
      this.$confirm('确定要借阅《' + row.bookname + '》这本书吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用 API，传递 bookid (从 row.bookid 获取) 和 username
        borrowBook(row.bookid, username).then(res => { // 修正：传递 row.bookid
          if (res.code === 200) {
            this.$message.success("借阅成功！");
            this.fetchAvailableBooks(); // 刷新图书列表以更新状态
          } else {
            this.$message.error(res.msg || "借阅失败");
          }
        }).catch(error => {
          console.error("借阅请求失败:", error);
          this.$message.error("借阅请求发送失败，请稍后再试。");
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消借阅'
        });
      });
    },
    handlePageChange(newPage) {
      this.currentPage = newPage;
      this.fetchAvailableBooks();
    },
    searchBooks() {
      this.currentPage = 1;
      this.fetchAvailableBooks();
    },
    resetSearch() {
      this.searchForm = {
        bookname: '',
        bookauthor: '',
        booktypeid: null,
        isborrowed: 0
      };
      this.currentPage = 1;
      this.fetchAvailableBooks();
    }
  }
};
</script>

<style scoped>
/* 可选的样式 */
.ReaderAvailableBooks {
  padding: 20px;
}
.demo-form-inline {
  margin-bottom: 20px;
}
</style>